'use strict';
const mongoose = require('mongoose');
const config = require('../config/config.unittest.js')({});
const fs = require('fs');
const readline = require('readline');
const moment = require('moment');
const _ = require('lodash');

let ParserBetter = require('../app/utils/rss/parser');
let parserBetter = new ParserBetter({timeout: 10000});

const UserModel = require('../app/model/User')({
  mongoose,
});
const TopicModel = require('../app/model/Topic')({
  mongoose,
});
const TopicCollectModel = require('../app/model/TopicCollect')({
  mongoose,
});
const MessageModel = require('../app/model/Message')({
  mongoose,
});


mongoose.connect(config.mongoose.url, config.mongoose.options, function (err) {
  if (err) {
    console.error('connect to %s error: ', config.mongoose, err.message);
    process.exit(1);
  }
});

main();

async function main() {
  await crud();
  process.exit(0);
}


async function crud() {
  let messages = await MessageModel.find();

  for (let i = 0; i < messages.length; i++) {
    console.log(i, messages.length);
    const message = messages[i];

    const master_user = await UserModel.findOne({_id: message.master_id}, {loginname: 1});
    message.master_name = master_user.loginname;
    const author_user = await UserModel.findOne({_id: message.author_id}, {loginname: 1});
    message.author_name = author_user.loginname;

    if (message.topic_id) {
      const topic = await TopicModel.findOne({_id: message.topic_id}, {title: 1});
      message.topic_title = topic.title;
    }

    const result = await message.save();
  }


}
